package cj.web.marry.controllers;

import java.net.URLEncoder;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.Page;
import cj.utils.ReturnUUID;
import cj.utils.weixin.HttpsWenXinUtil;
import cj.utils.weixin.pay.UnifiedOrder;
import cj.web.BaseController;
import cj.web.mall.dao.UserDAO;
import cj.web.marry.constants.EducationEnum;
import cj.web.marry.constants.MemberComTypeEnum;
import cj.web.marry.constants.SalaryEnum;
import cj.web.marry.constants.WXPayAttachEnum;
import cj.web.marry.dao.FollowDAO;
import cj.web.marry.dao.PubActDAO;
import cj.web.marry.dao.XQPubYHDAO;

@Path("pubAct")
public class PubActController extends BaseController{

	protected static final Log logger = LogFactory.getLog(PubActController.class); 
	
	@Autowired
	private PubActDAO pubActDAO;
	@Autowired
	private UserDAO userDao;
	@Autowired
	private XQPubYHDAO xqPubYHDAO;
	@Autowired
	private FollowDAO followDao;
	
	@Get("homeCode")  //活动页面Code
	public String homeCode(Model model,@Param("code")String code, HttpServletResponse response) throws Exception{
		Map oauth2Reps = HttpsWenXinUtil.retOauth2Infor(code, Constants.weixinkey.AppID, Constants.weixinkey.AppSecret);
		String openId = oauth2Reps.get("openid").toString();
		
//		String access_token = "5_t_0b1DfJd-miqaupR01BIoZkDZBL_FAVKk4TUW3_HTf9MQzfBzWD6tcJNVO0DSdSBmLDWVHckSPoQJOHq8xr9Q";
//		String openId = "ofwuNsyVHbXdpotCwZ_ZJLp7DSrQ";
		setCookie(response, "openId", openId);
		return "r:home";
	}
	
	@Get("home")  //活动页面
	public String home(Model model, HttpServletRequest request) throws Exception{
		Map<String, String> config = getConfigSign(request);
		model.add("Config",config);
		
		model.add("Title", "长江婚典商城-您的专属婚品");
		model.add("Desc", "只为您专属打造");
		model.add("LinkURL", oauth_start+request.getScheme() +"://" + request.getServerName() + "/pubAct/homeCode"+oauth_end);
		return "/views/marry/meet/latestActivity/latestActivity.vm";
	}
	
	@Get("getList")  //活动列表方法
	public String getList(@Param("start") int start,@Param("length") int length,
			Model model, HttpServletRequest request) throws Exception{
		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> gamels = pubActDAO.queryAllForEndDate(start*length,length);
		
		int totalCount = pubActDAO.queryAllForEndDateSize();
		//分页计算
		Page p= new Page<Map>(0, length, gamels, totalCount);
		jo.put("list", gamels);
		jo.put("repsize", p.getTotalPages());
		jo.put("totalCount", totalCount);
		
		return "@"+jo.toString();
	}
	
	@Get("detailCode")  //活动详情Code
	public String detailCode(Model model,@Param("code")String code, @Param("state")int gameId, HttpServletResponse response){
		String openId = HttpsWenXinUtil.retOpenId(code,Constants.weixinkey.AppID, Constants.weixinkey.AppSecret);
		setCookie(response, "openId", openId);
		return "r:detail?gameId=" + gameId;
	}
	
	/**
	 * 活动详情
	 * @param model
	 * @param gameId	活动ID
	 * @return
	 * @throws Exception 
	 */
	@Get("detail")
	public String detail(Model model,@Param("gameId")int gameId, HttpServletRequest request) throws Exception{
		List<Map> obj = pubActDAO.queryById(gameId);
		if(obj!=null && obj.size()>0){
			String endDate = obj.get(0).get("endDate").toString();
			int flagendDate = DateUtils.compareDateWithNow(DateUtils.parse(endDate));
			if(flagendDate>=0){
				model.add("flag", true);
			}else{
				model.add("flag", false);
			}
			String startDate = obj.get(0).get("startDate").toString();
			int flagstartDate = DateUtils.compareDateWithNow(DateUtils.parse(startDate));
			if(flagstartDate<=0){
				model.add("flag", true);
			}else{
				model.add("flag", false);
			}
			
			obj.get(0).put("startDate", DateUtils.getMinusTime(obj.get(0).get("startDate").toString(), DateUtils.DATE_SMALL_STR, 0));
			obj.get(0).put("endDate", DateUtils.getMinusTime(obj.get(0).get("endDate").toString(), DateUtils.DATE_SMALL_STR, 0));
			model.add("obj", obj.get(0));
			
			Map<String, String> config = getConfigSign(request);
			model.add("Config",config);
			String gameName = obj.get(0).get("name").toString();
			model.add("Title", gameName);
			model.add("Desc", gameName);
			model.add("LinkURL", oauth_start+request.getScheme() +"://" + request.getServerName() + "/pubAct/detailCode"+oauth_end);
		}
		
		return "/views/marry/meet/latestActivity/activityDetail.vm";
	}
	
	@Get("joinPubAct")  //参加活动
	public synchronized String detailCode(Model model,@Param("gameId")int gameId,HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			if( isLogin(request) ){
				String phone = getCookieValueByName(request, "phone");
				int buyerId = userDao.getBuyerId(phone);
				
				List<Map> userlis = userDao.getMemberDetailForUC(buyerId);
				
				if(userlis!=null && userlis.size()>0){
					//是否存在用户
					int count = pubActDAO.queryPubActivityOrderCount(buyerId, gameId);
					if(count==0){
						//没有参加
						String orderNo = ReturnUUID.getOrderNo("");
						List<Map> obj = pubActDAO.queryById(gameId);
						pubActDAO.createPubActOrder(gameId, orderNo, buyerId, 
								obj.get(0).get("duration").toString(), obj.get(0).get("price").toString(), phone);
						pubActDAO.updatePubActivity(gameId);
						
						String tmpPrice = String.valueOf(Float.parseFloat(obj.get(0).get("price").toString()) * 100);
						String total_fee = tmpPrice.substring(0, tmpPrice.indexOf("."));
						if(Integer.parseInt(total_fee)>0){
							//--------------调用微信接口
							//String total_fee = String.valueOf((Float.parseFloat(obj.get("discntPrice").toString()) * 100.0));
							String spbill_create_ip = request.getRemoteAddr();
							String notify_url = request.getScheme() +"://" + request.getServerName() + "/order/result";
					        String openId = getCookieValueByName(request, "openId");
					        if(openId != null && openId.length() > 0){
					        	UnifiedOrder unifiedOrder = new UnifiedOrder();
					    		Map prepay = unifiedOrder.getPrepayId("确认订单-我的活动", orderNo, total_fee, spbill_create_ip, notify_url, openId,WXPayAttachEnum.XQ.getValue());
					    		jo.put("rtn", prepay);
					    		return "@" + jo.toString();
					        }
					        else{
					        	String retPg = URLEncoder.encode("pubAct/detail?gameId=" + gameId, "utf-8");
								jo.put("returnPage", "../xqLoginPub/login?returnPage=" + retPg);
					        	jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
					        	return "@" + jo.toString();
					        }
							//--------------
						}
						
					}else{
						//已参加
						jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
					}
				}else{
					String retPg = URLEncoder.encode("pubAct/detail?gameId=" + gameId, "utf-8");
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
					jo.put("returnPage", "../xqLoginPub/login?returnPage=" + retPg);
				}
				
			}else{
				String retPg = URLEncoder.encode("pubAct/detail?gameId=" + gameId, "utf-8");
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnPage", "../xqLoginPub/login?returnPage=" + retPg);
			}
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 参加会员列表
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("pubMember")
	public String pubMember(Model model, HttpServletRequest request, @Param("gameId") String gameId) throws Exception{
		if( isLogin(request) ){
			
			String phone = getCookieValueByName(request, "phone");
			int buyerId = userDao.getBuyerId(phone);
			int isExist = userDao.isExistMemberDetail(buyerId);
			
			if(isExist==0){
				String retPg = URLEncoder.encode("pubAct/pubMember", "utf-8");
				return "r:../xqLoginPub/perfectUser?returnPage="+retPg;
			}
			
			Map<String, String> config = getConfigSign(request);
			model.add("Config",config);
			
			model.add("Title", "长江婚典商城-您的专属婚品");
			model.add("Desc", "只为您专属打造");
			model.add("LinkURL", oauth_start+request.getScheme() +"://" + request.getServerName() + "/pubAct/homeCode"+oauth_end);
		}else{
			String retPg = URLEncoder.encode("pubAct/pubMember", "utf-8");
			return "r:../xqLoginPub/login?returnPage=" + retPg;
		}
		
		model.add("EducationEnum",EnumSet.allOf(EducationEnum.class));
        model.add("SalaryEnum",EnumSet.allOf(SalaryEnum.class));
        model.add("gameId",gameId);
		return "/views/marry/meet/latestActivity/memberRecommend.vm";
	}
	
	/**
	 * 人员条件筛选
	 * @param model
	 * @param educationId	学历
	 * @param agePicker		年龄
	 * @param salaryPicker	月薪
	 * @param profession	职业
	 * @param city			地点
	 * @param dataOrder		排序号
	 * @param start
	 * @param length
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("pubMemberlis")
	public String pubMemberlis(Model model,@Param("gameId") String gameId,@Param("education") String education,
			@Param("agePicker") String agePicker,@Param("salaryPicker") String salaryPicker,@Param("profession") String profession,
			@Param("province") String province,@Param("dataOrder") String dataOrder,@Param("start") int start,
			@Param("length") int length, HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String phone = getCookieValueByName(request, "phone");
		int buyerId = userDao.getBuyerId(phone);
		
		List<Map> userls = userDao.getMemberDetailByUserId(buyerId);
		int sex = 1;
		if(userls!=null && userls.size()>0){
			sex = Integer.parseInt(userls.get(0).get("sex").toString());
		}
		
		//education 学历
		education =education.equals("不限")?"":education;
		//profession 职业
		int money = salaryPicker.equals("不限")?-1:SalaryEnum.getValue(salaryPicker);//月薪
		String area="";
		String city="";
		if(!province.equals("")){
			area=province.split(" ")[2];//区
			city=province.split(" ")[1];//市
			province=province.split(" ")[0];//省
		}
		agePicker =agePicker.equals("不限")?"":agePicker;
		
		//获取参与活动用户ID
		List<Integer> userIds = pubActDAO.queryPubActivityOrderByActId(Integer.parseInt(gameId));
		
		//dataOrder 0最新推荐	1热度降序	2年龄升序	3年龄降序
		List<Map> gamels = xqPubYHDAO.queryMemberDetailLisForPub(MemberComTypeEnum.NUM_0.getValue(),
				start*length,length,buyerId,sex, education, profession, money, area, city,
	    		 province, dataOrder,agePicker,userIds);
		
		for(Map rep:gamels){
//			int objectUserId = Integer.parseInt(rep.get("userId").toString());
			
//			int count = xqPubYHDAO.queryPubYHSize(buyerId, objectUserId, String.valueOf(XQYHStatusEnum.doing.getValue()));
//			if(count>0){
//				//已约
//				rep.put("flag", true);
//			}else{
//				//可以约
//				rep.put("flag", false);
//			}
			
//			int followCount = followDao.querySizeByUserId(buyerId, objectUserId);
//			if(followCount>0){
//				//已关注
//				rep.put("followFlag", true);
//			}else{
//				//未关注
//				rep.put("followFlag", false);
//			}
			
			rep.put("educationName", EducationEnum.getName(Integer.valueOf(rep.get("education").toString())));
		}
		
//		int totalCount = xqPubYHDAO.queryMemberDetailLisSize(MemberComTypeEnum.NUM_0.getValue(),buyerId,sex);
		//分页计算
//		Page p= new Page<Map>(0, length, gamels, totalCount);
		jo.put("list", gamels);
//		jo.put("repsize", p.getTotalPages());
//		jo.put("totalCount", totalCount);
		return "@"+jo.toString();
	}
}